
#include "gmatlab.h"

// mxArray * g_closure_matlab_invoke(GClosure *, Cell array);
void mexFunction(int nlhs, mxArray *lhs[], int nrhs, const mxArray *rhs[])
{
  GClosure *closure;
  
  // Check and convert arguments
  if (nrhs != 2) g_matlab_error("gmatlab:numArg", "g_closure_matlab_invoke() takes 2 arguments");
  if (nlhs != 1) g_matlab_error("gmatlab:numRet", "g_closure_matlab_invoke() has 1 return value");
  if (mxGetClassID(rhs[0]) != MX_GPOINTER) g_matlab_error("gmatlab:badType", "g_closure_matlab_invoke: Argument 1 must be int, not %s", mxGetClassName(rhs[0]));
  closure = ((gpointer*)mxGetData(rhs[0]))[0];
  if (!closure) g_matlab_error("gmatlab:badType", "g_closure_matlab_invoke: Closure cannot be NULL");
  if (mxGetClassID(rhs[1]) != mxCELL_CLASS) g_matlab_error("gmatlab:badType", "g_closure_matlab_invoke: Argument 2 must be cell, not %s", mxGetClassName(rhs[1]));
  
  // Call function
  g_matlab_escape_init();
  lhs[0] = g_closure_matlab_invoke(closure, rhs[1]);
  g_matlab_escape_clear();
  g_matlab_cleanup();
}
